package com.apex.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.Instant;

/**
 * 日志过滤器
 *
 * @author MoNaiHui
 */
@Slf4j
@Component
public class RequestLogFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        String method = request.getMethod().name();
        MultiValueMap<String, String> queryParams = request.getQueryParams();

        long startTime = Instant.now().toEpochMilli();

        // 使用 emoji 和简洁格式记录请求信息
        log.info("🚀 请求开始 >>> {} [{}] params={}", method, path, queryParams);

        return chain.filter(exchange)
                .then(Mono.fromRunnable(() -> {
                    long timeElapsed = Instant.now().toEpochMilli() - startTime;
                    // 使用 emoji 记录响应时间
                    log.info("✨ 请求结束 <<< {} 耗时{}ms", path, timeElapsed);
                }));
    }
    
    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
